<template>
  <view class="bankcard_info_view need_scroll_top_view">
    <view class="form-wrap">
      <form>
        <view class="form-item">
          <text class="form-item-label">是否公款账户</text>
          <picker :value="commonIndex" :range="isCommonBank" @change="bindCommonBankPickerChange" class="form-item-pick">
            <view :class="{'pick-value': !commonIndex, 'pick-value-select': commonIndex}" v-if="isCommonBank && isCommonBank.length > 0">{{isCommonBank[commonIndex]}}</view>
          </picker>
          <view class="arrow"></view>
        </view>
        <view class="cut-line"></view>
        <view class="form-item self-border-bottom">
          <text class="form-item-label">账户名称</text>
          <input type="text" v-model="data.name" class="form-item-input" placeholder="请填写持卡人姓名" placeholder-class="input-placeholder" @blur="backFixationTop()" disabled />
          <view class="no-arrow"></view>
        </view>
        <view class="form-item self-border-bottom">
          <text class="form-item-label">开户银行</text>
          <picker :value="bankIndex" :range="bankArray" @change="bindBankPickerChange" class="form-item-pick" range-key="name" :disabled="!canEdit">
            <view :class="{'pick-value': !bankArray[bankIndex].id, 'pick-value-select': bankArray[bankIndex].id}" v-if="bankArray && bankArray.length > 0">{{bankArray[bankIndex].name}}</view>
            <!-- <view class="pick-value" v-else @click="openBnakList">请选择开户银行</view> -->
          </picker>
          <view class="arrow"></view>
        </view>
        <view class="form-item self-border-bottom">
          <text class="form-item-label">银行地址</text>
          <picker :value="multiDistrictIndex" range-key="name" :range="multiDistrictArray" @cancel="bindDistrictPickerCancel" @change="bindDistrictPickerChange" @columnchange="bindDistrictColumnPickerChange" class="form-item-pick" mode="multiSelector" :disabled="!canEdit">
            <view class="pick-value-select" v-if="multiDistrictArray && multiDistrictArray.length > 0 && selectDistrict">
              <text v-if="multiDistrictArray[0] && multiDistrictArray[0][multiDistrictIndex[0]]">{{multiDistrictArray[0][multiDistrictIndex[0]].name}}</text>
              <text v-if="multiDistrictArray[1] && multiDistrictArray[1][multiDistrictIndex[1]]">{{multiDistrictArray[1][multiDistrictIndex[1]].name}}</text>
              <text v-if="multiDistrictArray[2] && multiDistrictArray[2][multiDistrictIndex[2]]">{{multiDistrictArray[2][multiDistrictIndex[2]].name}}</text>
            </view>
            <view class="pick-value" v-else>请选择银行所在城市</view>
          </picker>
          <view class="arrow"></view>
        </view>
        <view class="form-item self-border-bottom">
          <text class="form-item-label">开户支行</text>
          <input type="text" v-model="data.branchBankName" class="form-item-input" placeholder="请填写开户支行" placeholder-class="input-placeholder" :disabled="!canEdit" @blur="backFixationTop()"/>
          <view class="no-arrow"></view>
        </view>
        
        <view class="form-item">
          <text class="form-item-label">银行卡号</text>
          <input type="number" v-model="data.cardNumber" class="form-item-input" placeholder="请填写银行卡号" placeholder-class="input-placeholder" @blur="backFixationTop()" :disabled="!canEdit"/>
          <view class="no-arrow"></view>
        </view>
      </form>
    </view>
    
    <view class="qrcode_selected_platform-footer">
      <button type="primary" class="qrcode_selected_platform-footer-btn" @click="nextStep" :disabled="!canEdit">确定</button>
    </view>
  </view>
</template>

<script>
import formValid from '@/unit/graceChecker.js'
import { multiDistrict } from '@/unit/common.js'
import { BankCardFindBankPageSyncApi, BankCardSaveBankCard, findBankUserProfileApi} from '@/service/user/user.service.js'
import { scrollToTargetPosition } from '@/mixin/index.mixin.js'
import { FindByUserId } from '@/service/user/user.service.js';
export default {
  mixins: [scrollToTargetPosition],
  data () {
    return {
      canEdit: false, // 是否可以填写数据，需要根据当前选择的公户还是私户判断当前用户当前条件下是否可以添加选择的相应类型的银行卡
      operationType: null, // 用来判断是从哪里来的 1：来自提现添加银行卡 2：来自用户中心添加银行卡
      bankArray: [], // 银行列表
      bankIndex: 0,
      commonIndex: 0,
      selectBank: false,
      selectDistrict: false,
      multiDistrictIndex: [], // 省市区选择的index
      multiDistrictArray: [], // 省市区数据 Array[Object]
      multiDistrictIds: [], // 省市区ID
      originMultiDistrictIndex: [], // 原始数据 用于取消选择省市区，还原原始数据
      originMultiDistrictArray: [], // 原始数据 用于取消选择省市区，还原原始数据
      originMultiDistrictIds: [], // 原始数据 用于取消选择省市区，还原原始数据
      data: {
        name: '', // 账户名称
        cardNumber: '', // 银行卡号
        bankName: '', // 开户银行
        bankId: null,
        districtId: null, // 银行地址
        branchBankName: '', // 开户支行
        identify: '' // 是否是对公账户
      },
      isCommonBank: [
        '请选择',
        '是',
        '否'
      ]
    }
  },
  mounted () {},
  methods: {
    bindCommonBankPickerChange (e) {
      this.commonIndex = e.target.value;
      this.data.identify = e.target.value == 1 ? 0 : e.target.value == 2 ? 1 : '';
      if (e.target.value != 0) {
        this.isCanAddBankCard(this.data.identify);
      }
    },
    isCanAddBankCard (type) { // 根据当前选择的账户类型请求接口判断是否可以添加当前账户类型的数据
      findBankUserProfileApi({
        id: type
      }, res => {
        if (res.status == 0) {
          if (res.data.userIdentityStatus == 0) {
            if (type == 0) { // type：0 对公账户, 需要验证是否已经营业执照审核通过
              if (res.data.joinType == 1) { // joinType: 1 个人加盟 
                uni.showModal({
                  title: '',
                  content: '个人加盟用户不能添加对公账户！',
                  confirmText: '知道了',
                  showCancel: false,
                  confirmColor: '#F6DA99',
                  success: (res) => {
                    if (res.confirm) {
                      // uni.redirectTo({
                      //   url: this.operationType == 1 ? '/pages/cashWithDrawal/index' : '/pages/user/bankCardList'
                      // });
                    }
                  }
                })
              } else if (res.data.userQualificationStatus == 1) {
                this.data.name = res.data.userName;
                this.canEdit = true;
              } else if (res.data.userQualificationStatus == 0) {
                uni.showModal({
                  title: '',
                  content: '您的营业执照正在审核中，请耐心等待！',
                  confirmText: '知道了',
                  showCancel: false,
                  confirmColor: '#F6DA99',
                  success: (res) => {
                    if (res.confirm) {
                      uni.redirectTo({
                        url: this.operationType == 1 ? '/pages/cashWithDrawal/index' : '/pages/user/bankCardList'
                      });
                    }
                  }
                })
              } else if (res.data.userQualificationStatus == 2) {
                uni.showModal({
                  title: '',
                  content: '您的营业执照审核失败，请重新上传！',
                  confirmText: '去上传',
                  cancelText: '取消',
                  confirmColor: '#F6DA99',
                  cancelColor: '#434343',
                  success: (res) => {
                    if (res.confirm) {
                      uni.navigateTo({
                        url: '/pages/certificationReplenish/updateLicense?status=1'
                      })
                    } else if (res.cancel) {
                      uni.redirectTo({
                        url: this.operationType == 1 ? '/pages/cashWithDrawal/index' : '/pages/user/bankCardList'
                      });
                    }
                  }
                })
              } else if (res.data.userQualificationStatus == 3) {
                uni.showModal({
                  title: '',
                  content: '您的营业执照审核被驳回，请重新上传！',
                  confirmText: '去实名认证',
                  cancelText: '取消',
                  confirmColor: '#F6DA99',
                  cancelColor: '#434343',
                  success: (res) => {
                    if (res.confirm) {
                      uni.navigateTo({
                        url: '/pages/certificationReplenish/updateLicense?status=1'
                      })
                    } else if (res.cancel) {
                      uni.redirectTo({
                        url: this.operationType == 1 ? '/pages/cashWithDrawal/index' : '/pages/user/bankCardList'
                      });
                    }
                  }
                })
              }
            } else if (type == 1) { // type：1 对私账户，需要验证是否已经实名认证
              this.data.name = res.data.name;
              this.canEdit = true;
            }
          } else {
            this.getRealNameInfo();
          }
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      });
    },
    async initDistrictData (district) { // 初始化省市区数据
      let {multiDistrictArray, multiDistrictIndex, multiDistrictIds} = await multiDistrict.initMultDistrictArray({
        district: district
      });
      this.multiDistrictArray = multiDistrictArray;
      this.multiDistrictIndex = multiDistrictIndex;
      this.multiDistrictIds = multiDistrictIds;
      this.originMultiDistrictArray = JSON.parse(JSON.stringify(multiDistrictArray));
      this.originMultiDistrictIndex = JSON.parse(JSON.stringify(multiDistrictIndex));
      this.originMultiDistrictIds = JSON.parse(JSON.stringify(multiDistrictIds));
      // this.data.districtId = this.multiDistrictIds[this.multiDistrictIds.length - 1];
    },
    bindDistrictPickerCancel (e) { // 取消省市区的选择
      this.multiDistrictArray = JSON.parse(JSON.stringify(this.originMultiDistrictArray));
      this.multiDistrictIndex = JSON.parse(JSON.stringify(this.originMultiDistrictIndex));
      this.multiDistrictIds = JSON.parse(JSON.stringify(this.originMultiDistrictIds));
    },
    bindDistrictPickerChange (e) { // 确认省市区的选择
      this.selectDistrict = true;
      this.originMultiDistrictArray = JSON.parse(JSON.stringify(this.multiDistrictArray));      
      this.originMultiDistrictIndex = JSON.parse(JSON.stringify(this.multiDistrictIndex));
      this.originMultiDistrictIds = JSON.parse(JSON.stringify(this.multiDistrictIds));
      this.data.districtId = this.multiDistrictIds[this.multiDistrictIds.length - 1];
    },
    async bindDistrictColumnPickerChange (e) { // 省市区的列发生变化
      if (e.detail.column < this.multiDistrictArray.length - 1) {
        let {multiDistrictArray, multiDistrictIndex, multiDistrictIds} = await multiDistrict.bindDistrictColumnPickerChange({
          column: e.detail.column,
          index: e.detail.value,
          multiDistrictIndex: JSON.parse(JSON.stringify(this.multiDistrictIndex)),
          multiDistrictArray: JSON.parse(JSON.stringify(this.multiDistrictArray))
        });
        this.multiDistrictArray = multiDistrictArray;
        this.multiDistrictIndex = multiDistrictIndex;
        this.multiDistrictIds = multiDistrictIds;
      } else {
        this.multiDistrictIndex.splice(e.detail.column, 1, e.detail.value);
        this.multiDistrictIds.splice(e.detail.column, 1, this.multiDistrictArray[e.detail.column][e.detail.value].id);
      }
    },
    bindBankPickerChange (e) {
      this.selectBank = true;
      this.bankIndex = e.target.value;
      this.data.bankId = this.bankArray[e.target.value].id;
      this.data.bankName = this.bankArray[e.target.value].name;
    },
    nextStep () {
      let that = this;
      let rule = [
        {name:'bankId', checkType : 'notnull', checkRule:'',  errorMsg:'请选择开户银行'},
        {name:'districtId', checkType : 'notnull', checkRule:'',  errorMsg:'请填写银行地址'},
        {name:'branchBankName', checkType : 'notnull', checkRule:'',  errorMsg:'请填写开户支行'},
        {name:'cardNumber', checkType : 'notnull', checkRule:'',  errorMsg:'请填写银行卡号'},
        {name:'name', checkType : 'notnull', checkRule:'',  errorMsg:'请填写账户名称'},
        {name:'identify', checkType : 'notnull', checkRule:'',  errorMsg:'请选择是否是对公账户'},
      ];
      var checkRes = formValid.check(this.data, rule);
      if (checkRes) {
        let params = Object.assign(this.data);
        BankCardSaveBankCard(params, res => {
          if (res.status == 0) {
            uni.showToast({
              title: '保存银行卡成功！',
              icon: 'none',
              success: () => {
                setTimeout(function () {
                  uni.redirectTo({
                    url: '/pages/user/bankCardList' + (this.operationType == 1 ? '?operationType=1' : '')
                  });
                }, 2000);
              }
            });
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            });
          }
        });
      } else {
        uni.showToast({ title: formValid.error, icon: "none" });
      }
    },
    async init () {
      let data = await BankCardFindBankPageSyncApi({
        size: 1000,
        current: 1
      });
      this.bankArray = data.records;
      this.bankArray.unshift({
        name: '请选择开户银行',
        id: null,
        code: ''
      });
      this.initDistrictData();
    },
    getRealNameInfo () {
      FindByUserId({}, res => {
        if (res.status == 0 && res.data.id) {
          if (res.data.status == 2) {
            uni.showModal({
              title: '',
              content: '您的实名认证正在审核中，审核通过之后即可添加银行卡，请耐心等待！',
              confirmText: '知道了',
              showCancel: false,
              confirmColor: '#F6DA99',
              // cancelColor: '#434343',
              success: (res) => {
                if (res.confirm) {
                  uni.redirectTo({
                    url: this.operationType == 1 ? '/pages/cashWithDrawal/index' : '/pages/user/bankCardList'
                  });
                }
              }
            })
          } else if (res.data.status == 1) {
            uni.showModal({
              title: '',
              content: '您的实名认证审核失败，请重新实名认证！',
              confirmText: '去实名认证',
              cancelText: '取消',
              confirmColor: '#F6DA99',
              cancelColor: '#434343',
              success: (res) => {
                if (res.confirm) {
                  uni.navigateTo({
                    url: '/pages/user/realNameAuthentication'
                  })
                } else if (res.cancel) {
                  uni.redirectTo({
                    url: this.operationType == 1 ? '/pages/cashWithDrawal/index' : '/pages/user/bankCardList'
                  });
                }
              }
            })
          }
        } else if (res.status == 0 && !res.data.id) { // 判断是否已经实名认证，如果已经实名认证，可以添加银行卡，否则需要优先填写实名认证
          uni.showModal({
            title: '',
            content: '添加银行卡之前必须完成实名认证，是否去实名认证',
            confirmText: '去实名认证',
            cancelText: '取消',
            confirmColor: '#F6DA99',
            cancelColor: '#434343',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/user/realNameAuthentication'
                })
              } else if (res.cancel) {
                uni.redirectTo({
                  url: this.operationType == 1 ? '/pages/cashWithDrawal/index' : '/pages/user/bankCardList'
                });
              }
            }
          })
        }
      });
    }
  },
  onShow () {
    this.init();
    this.getRealNameInfo();
    // this.getBankList();
  },
  onLoad (option) {
    this.operationType = option.operationType;
    // this.init(option);
  }
}
</script>

<style lang="scss" scoped>
  .bankcard_info_view {
    position: relative;
    height: 100vh;
    .form-wrap {
      background: #FFFFFF;
      .self-border-bottom {
        border-bottom: 1rpx solid #E1E1E1;
      }
      .self-margin-top {
        margin-top: 22rpx;
      }
      .cut-line {
        height: 22rpx;
        background-color: #FAFAFA;
      }
      
      .pick-value-select {
        color: #333333;
        font-size: 28rpx;
      }
      
      .pick-value {
        color: #999999;
        font-size: 24rpx;
      }
      .form-item {
        display: flex;
        width: 718rpx;
        justify-content: center;
        align-items: center;
        margin-left: 32rpx;
        // height: 100rpx;
        padding: 36rpx 0;
        
        .form-item-label {
          width: 180rpx;
          text-align: left;
          padding: 0 32rpx 0 0;
          font-size: 28rpx;
          color: #333333;
          font-weight:500;
        }
        .form-item-input {
          font-size: 28rpx;
          height: 38rpx;
          color: #333333;
          flex: 1;
          .input-placeholder {
            font-size: 24rpx;
            color: #999999;
          }
        }
        .form-item-pick {
          flex: 1;
        }
        .arrow {
          margin-right: 33rpx;
          border-right: 3rpx solid #8A8A8A;
          border-top: 3rpx solid #8A8A8A;
          height: 18rpx;
          width: 18rpx;
          transform: rotate(45deg);
          -webkit-transform: rotate(45deg);
          /*不加这两个属性三角会比上一个略丑, 大家可以试一下*/
          border-left: 2rpx solid transparent;
          border-bottom: 2rpx solid transparent;
        }
        .no-arrow {
          margin-left: 64rpx;
        } 
      }
      
      .form-other-item {
        padding: 0 34rpx 22rpx;
        .form-item-head {
          overflow: hidden;
          padding-top: 40rpx;
          .title {
            float: left;
            color: #333333;
            font-size: 36rpx;
          }
          .sample {
            float: right;
            text {
              color: #FF7473;
              font-size: 28rpx;
              text-decoration: underline;
            }
          }
          &:after {
            clear: both;
          }
        }
        .form-item-content {
          margin-top: 30rpx;
          .common-img-wrap {
            width: 330rpx;
            height: 200rpx;
            border: 1px dashed #E1E1E1;
            border-radius: 16rpx;
            
            .no-upload-img {
              width: 100%;
              height: 100%;
              display: flex;
              flex-flow: column;
              align-items: center;
              justify-content: center;
              .img {
                width: 80rpx;
                height: 80rpx;
              }
              .text {
                margin-top: 29rpx;
                color: #666666;
                font-size: 24rpx;
                font-weight:500;
              }
            }
            
            .upload-img-wrap {
              width: 100%;
              height: 100%;
              
              .upload-img {
                width: 100%;
                height: 100%;
                border-radius: 16rpx;
              }
            }
          }
          .upload-img-wrap {
            width: 100%;
            height: 100%;
            
            .upload-img {
              width: 100%;
              height: 100%;
              border-radius: 16rpx;
            }
          }
        }
      }
    }
    
    .qrcode_selected_platform-footer {
      position: absolute;
      bottom: 0rpx;
      left: 0rpx;
      width: 100%;
      height: 105rpx;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      border-top: 1rpx solid #E1E1E1;
      background: #FFFFFF;
      .qrcode_selected_platform-footer-btn {
        width: 687rpx;
        height: 70rpx;
        background-color: #434343;
        color: #F6DA99;
        font-size: 30rpx;
      }
    }
  }
</style>
